#include "frmserialport.h"
#include "ui_frmserialport.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QMessageBox>
#include <QThread>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "frmmain.h"

frmserialport::frmserialport(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::frmserialport),
    mainWindow(qobject_cast<frmmain*>(parent)),
    isConfigMode(false),
    isWaitingForResponse(false),
    lastCommand(""),
    currentQueryTab(-1),
    isWaitingForTcpConfig(false)
{
    ui->setupUi(this);

    // 填充可用串口
    populateSerialPorts();

    // 设置默认波特率
    ui->baudRateComboBox->setCurrentText("115200");

    // 连接信号和槽
    connect(ui->baseStationAutoCheckBox, &QCheckBox::toggled, this, [this](bool checked) {
        ui->baseStationLatLineEdit->setEnabled(!checked);
        ui->baseStationLonLineEdit->setEnabled(!checked);
        ui->baseStationHeightLineEdit->setEnabled(!checked);
    });

    connect(ui->portComboBox, &QComboBox::currentTextChanged, this, &frmserialport::updateSendConfigButtonState);
    connect(ui->baudRateComboBox, &QComboBox::currentTextChanged, this, &frmserialport::updateSendConfigButtonState);

    // 连接 frmmain 的 serialDataReceived 信号
    if (mainWindow) {
        connect(mainWindow, &frmmain::serialDataReceived, this, &frmserialport::onSerialDataReceived);
    }

    // 设置超时定时器
    responseTimer.setSingleShot(true);
    connect(&responseTimer, &QTimer::timeout, this, &frmserialport::onResponseTimeout);

    // 初始时更新按钮状态
    updateSendConfigButtonState();
    enableTcpConfigControls(false);
}

frmserialport::~frmserialport()
{
    delete ui;
}

void frmserialport::populateSerialPorts()
{
    ui->portComboBox->clear();
    QList<QSerialPortInfo> ports = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &port : ports) {
        ui->portComboBox->addItem(port.portName());
    }
}

void frmserialport::updateSendConfigButtonState()
{
    bool isPortSet = !ui->portComboBox->currentText().isEmpty();
    bool isBaudRateSet = !ui->baudRateComboBox->currentText().isEmpty();
    bool isConnected = mainWindow && mainWindow->getIsSerialConnected();
    bool enable = isPortSet && isBaudRateSet && isConnected && isConfigMode;
    ui->sendConfigButton->setEnabled(enable);
    ui->enterConfigModeButton->setEnabled(isConnected && !isConfigMode);
    ui->exitConfigModeButton->setEnabled(isConnected && isConfigMode);
}

void frmserialport::updateMainResponse(const QString &msg)
{
    if (mainWindow) {
        QTextEdit *responseTextEdit = mainWindow->findChild<QTextEdit*>("responseTextEdit");
        if (responseTextEdit) {
            responseTextEdit->append(msg);
            responseTextEdit->repaint();
        }
    }
}

void frmserialport::onResponseTimeout()
{
    if (isWaitingForResponse) {
        updateMainResponse("错误：设备未响应，查询超时");
        isWaitingForResponse = false;
        isWaitingForTcpConfig = false;
    }
}

void frmserialport::on_connectButton_clicked()
{
    QSerialPort *serialPort = mainWindow->getSerialPort();

    if (serialPort->isOpen()) {
        if (isConfigMode) {
            sendConfigModeCommand(false);
        }
        serialPort->close();
        ui->connectButton->setText("连接");
        ui->enterConfigModeButton->setEnabled(false);
        ui->exitConfigModeButton->setEnabled(false);
        enableConfigControls(false);
        mainWindow->setIsSerialConnected(false);
        updateMainResponse("串口连接已断开");
    } else {
        QString portName = ui->portComboBox->currentText();
        QString baudRate = ui->baudRateComboBox->currentText();

        if (portName.isEmpty()) {
            updateMainResponse("错误：请选择一个串口");
            return;
        }

        serialPort->setPortName(portName);
        serialPort->setBaudRate(baudRate.toInt());
        serialPort->setDataBits(QSerialPort::Data8);
        serialPort->setParity(QSerialPort::NoParity);
        serialPort->setStopBits(QSerialPort::OneStop);
        serialPort->setFlowControl(QSerialPort::NoFlowControl);

        if (serialPort->open(QIODevice::ReadWrite)) {
            ui->connectButton->setText("断开");
            ui->enterConfigModeButton->setEnabled(true);
            mainWindow->setIsSerialConnected(true);
            updateMainResponse("串口连接已建立: " + portName + " @ " + baudRate);
        } else {
            updateMainResponse("错误：无法打开串口 - " + serialPort->errorString());
        }
    }
    updateSendConfigButtonState();
}

void frmserialport::on_enterConfigModeButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }

    sendConfigModeCommand(true);
    isConfigMode = true;
    ui->enterConfigModeButton->setEnabled(false);
    ui->exitConfigModeButton->setEnabled(true);
    enableConfigControls(true);
    updateSendConfigButtonState();
}

void frmserialport::on_exitConfigModeButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }

    sendConfigModeCommand(false);
    isConfigMode = false;
    ui->enterConfigModeButton->setEnabled(true);
    ui->exitConfigModeButton->setEnabled(false);
    enableConfigControls(false);
    updateSendConfigButtonState();
}

void frmserialport::on_sendBaseStationButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }
    if (!isConfigMode) {
        updateMainResponse("错误：请先进入设置模式");
        return;
    }

    QString command;
    bool ok;
    QSerialPort *serialPort = mainWindow->getSerialPort();

    if (ui->baseStationAutoCheckBox->isChecked()) {
        command = "$MODE,1\r\n";
        updateMainResponse("准备下发基准站配置（自动模式）...");
    } else {
        double lat = ui->baseStationLatLineEdit->text().toDouble(&ok);
        if (!ok) {
            updateMainResponse("错误：纬度必须为数字");
            return;
        }
        double lon = ui->baseStationLonLineEdit->text().toDouble(&ok);
        if (!ok) {
            updateMainResponse("错误：经度必须为数字");
            return;
        }
        double height = ui->baseStationHeightLineEdit->text().toDouble(&ok);
        if (!ok) {
            updateMainResponse("错误：高度必须为数字");
            return;
        }
        command = QString("$MODE,1,%1,%2,%3\r\n").arg(lat).arg(lon).arg(height);
        updateMainResponse("准备下发基准站配置（手动模式）...");
    }

    lastCommand = command.trimmed();
    isWaitingForResponse = true;
    serialPort->write(command.toUtf8());
    serialPort->flush();
    updateMainResponse("发送: " + command.trimmed());
    startResponseTimer();
}

void frmserialport::on_sendMobileStationButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }
    if (!isConfigMode) {
        updateMainResponse("错误：请先进入设置模式");
        return;
    }

    QString command = "$MODE,0\r\n";
    QSerialPort *serialPort = mainWindow->getSerialPort();

    lastCommand = command.trimmed();
    isWaitingForResponse = true;
    serialPort->write(command.toUtf8());
    serialPort->flush();
    updateMainResponse("发送: " + command.trimmed());
    startResponseTimer();
}

void frmserialport::on_sendConfigButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }
    if (!isConfigMode) {
        updateMainResponse("错误：请先进入设置模式");
        return;
    }

    int currentTabIndex = ui->tabWidgetConfig->currentIndex();
    QString command;
    bool ok;
    QSerialPort *serialPort = mainWindow->getSerialPort();

    switch (currentTabIndex) {
    case 0: // NMEA 配置
    {
        int msgId = ui->nmeaMsgIdComboBox->currentIndex();
        double nmeaRate = ui->nmeaRateLineEdit->text().toDouble(&ok);
        if (!ok || (nmeaRate != 0 && nmeaRate != 1 && nmeaRate != 0.5 && nmeaRate != 0.2)) {
            updateMainResponse("错误：NMEA 频率必须为 0、1、0.5 或 0.2");
            return;
        }
        command = QString("$NMEA,%1,%2\r\n").arg(msgId).arg(nmeaRate, 0, 'g', 0);
        updateMainResponse("准备下发 NMEA 配置...");
        break;
    }
    case 1: // RTCM 配置
    {
        int msgType = ui->rtcmMsgTypeLineEdit->text().toInt(&ok);
        if (!ok) {
            updateMainResponse("错误：RTCM 消息类型必须为整数");
            return;
        }
        double rtcmRate = ui->rtcmRateLineEdit->text().toDouble(&ok);
        if (!ok || (rtcmRate != 0 && rtcmRate != 1 && rtcmRate != 0.5 && rtcmRate != 0.2)) {
            updateMainResponse("错误：RTCM 频率必须为 0、1、0.5 或 0.2");
            return;
        }
        command = QString("$RTCM,%1,%2\r\n").arg(msgType).arg(rtcmRate, 0, 'g', 0);
        updateMainResponse("准备下发 RTCM 配置...");
        break;
    }
    case 2: // 基准站/移动站配置
    {
        if (ui->baseStationAutoCheckBox->isChecked()) {
            command = "$MODE,1\r\n";
            updateMainResponse("准备下发基准站配置（自动模式）...");
        } else {
            double lat = ui->baseStationLatLineEdit->text().toDouble(&ok);
            if (!ok) {
                updateMainResponse("错误：纬度必须为数字");
                return;
            }
            double lon = ui->baseStationLonLineEdit->text().toDouble(&ok);
            if (!ok) {
                updateMainResponse("错误：经度必须为数字");
                return;
            }
            double height = ui->baseStationHeightLineEdit->text().toDouble(&ok);
            if (!ok) {
                updateMainResponse("错误：高度必须为数字");
                return;
            }
            command = QString("$MODE,1,%1,%2,%3\r\n").arg(lat).arg(lon).arg(height);
            updateMainResponse("准备下发基准站配置（手动模式）...");
        }
        break;
    }
    case 3: // 陀螺计配置
    {
        double gyroRate = ui->gyroRateLineEdit->text().toDouble(&ok);
        if (!ok) {
            updateMainResponse("错误：陀螺计频率必须为数字");
            return;
        }
        command = QString("$GYRO,%1\r\n").arg(gyroRate, 0, 'g', 0);
        updateMainResponse("准备下发陀螺计配置...");
        break;
    }
    case 4: // 加速度计配置
    {
        double accelRate = ui->accelRateLineEdit->text().toDouble(&ok);
        if (!ok) {
            updateMainResponse("错误：加速度计频率必须为数字");
            return;
        }
        command = QString("$ACEL,%1\r\n").arg(accelRate, 0, 'g', 0);
        updateMainResponse("准备下发加速度计配置...");
        break;
    }
    case 5: // TCP 配置
    {
        QString tcpIp = ui->tcpIpLineEdit->text().trimmed();
        QString tcpPort = ui->tcpPortLineEdit->text().trimmed();
        QString tcpDevId = ui->tcpDevIdLineEdit->text().trimmed();

        if (tcpIp.isEmpty() || tcpPort.isEmpty() || tcpDevId.isEmpty()) {
            updateMainResponse("错误：TCP IP、端口和设备 ID 不能为空");
            return;
        }

        int port = tcpPort.toInt(&ok);
        if (!ok || port < 1 || port > 65535) {
            updateMainResponse("错误：TCP 端口号必须为 1-65535 之间的整数");
            return;
        }

        command = QString("$TCPS,%1,%2,%3\r\n").arg(tcpIp).arg(port).arg(tcpDevId);
        updateMainResponse("准备下发 TCP 配置...");
        break;
    }
    default:
        updateMainResponse("错误：未知的配置页面");
        return;
    }

    lastCommand = command.trimmed();
    isWaitingForResponse = true;
    serialPort->write(command.toUtf8());
    serialPort->flush();
    updateMainResponse("发送: " + command.trimmed());
    startResponseTimer();

    sendConfigModeCommand(false);
    isConfigMode = false;
    ui->enterConfigModeButton->setEnabled(true);
    ui->exitConfigModeButton->setEnabled(false);
    enableConfigControls(false);
}

void frmserialport::on_cancelButton_clicked()
{
    if (isConfigMode) {
        if (mainWindow->getIsSerialConnected()) {
            sendConfigModeCommand(false);
        }
        isConfigMode = false;
        ui->enterConfigModeButton->setEnabled(true);
        ui->exitConfigModeButton->setEnabled(false);
    }

    resetConfigFields();
    enableConfigControls(false);
    updateMainResponse("已取消操作，配置已重置");
}

void frmserialport::on_saveConfigButton_clicked()
{
    QJsonObject configObject;

    QJsonObject nmeaConfig;
    nmeaConfig["msgId"] = ui->nmeaMsgIdComboBox->currentIndex();
    nmeaConfig["rate"] = ui->nmeaRateLineEdit->text();
    configObject["nmea"] = nmeaConfig;

    QJsonObject rtcmConfig;
    rtcmConfig["msgType"] = ui->rtcmMsgTypeLineEdit->text();
    rtcmConfig["rate"] = ui->rtcmRateLineEdit->text();
    configObject["rtcm"] = rtcmConfig;

    QJsonObject baseStationConfig;
    baseStationConfig["autoMode"] = ui->baseStationAutoCheckBox->isChecked();
    baseStationConfig["latitude"] = ui->baseStationLatLineEdit->text();
    baseStationConfig["longitude"] = ui->baseStationLonLineEdit->text();
    baseStationConfig["height"] = ui->baseStationHeightLineEdit->text();
    configObject["baseStation"] = baseStationConfig;

    QJsonObject gyroConfig;
    gyroConfig["rate"] = ui->gyroRateLineEdit->text();
    configObject["gyro"] = gyroConfig;

    QJsonObject accelConfig;
    accelConfig["rate"] = ui->accelRateLineEdit->text();
    configObject["accel"] = accelConfig;

    QJsonObject tcpConfig;
    tcpConfig["ip"] = ui->tcpIpLineEdit->text();
    tcpConfig["port"] = ui->tcpPortLineEdit->text();
    tcpConfig["devId"] = ui->tcpDevIdLineEdit->text();
    configObject["tcp"] = tcpConfig;

    QFile file("serial_config.json");
    if (!file.open(QIODevice::WriteOnly)) {
        updateMainResponse("错误：无法打开文件 serial_config.json 进行写入");
        return;
    }

    QJsonDocument doc(configObject);
    file.write(doc.toJson());
    file.close();

    updateMainResponse("配置已保存到 serial_config.json");
}

void frmserialport::on_loadConfigButton_clicked()
{
    if (!mainWindow->getIsSerialConnected()) {
        updateMainResponse("错误：请先建立串口连接");
        return;
    }

    if (!isConfigMode) {
        updateMainResponse("错误：请先进入设置模式");
        return;
    }

    int currentTabIndex = ui->tabWidgetConfig->currentIndex();
    QString command;
    QSerialPort *serialPort = mainWindow->getSerialPort();

    switch (currentTabIndex) {
    case 0: // NMEA 配置
    {
        int msgId = ui->nmeaMsgIdComboBox->currentIndex();
        command = QString("$NMEA,?,%1\r\n").arg(msgId);
        updateMainResponse("正在查询 NMEA 配置...");
        break;
    }
    case 1: // RTCM 配置
    {
        bool ok;
        int msgType = ui->rtcmMsgTypeLineEdit->text().toInt(&ok);
        if (!ok) {
            updateMainResponse("错误：RTCM 消息类型必须为整数");
            return;
        }
        command = QString("$RTCM,?,%1\r\n").arg(msgType);
        updateMainResponse("正在查询 RTCM 配置...");
        break;
    }
    case 2: // 基准站/移动站配置
    {
        command = "$MODE,?\r\n";
        updateMainResponse("正在查询基准站/移动站配置...");
        break;
    }
    case 3: // 陀螺计配置
    {
        command = "$GYRO,?\r\n";
        updateMainResponse("正在查询陀螺计配置...");
        break;
    }
    case 4: // 加速度计配置
    {
        command = "$ACEL,?\r\n";
        updateMainResponse("正在查询加速度计配置...");
        break;
    }
    case 5: // TCP 配置
    {
        command = "$TCPS,?\r\n";
        updateMainResponse("正在查询 TCP 配置...");
        resetTcpConfigFields();
        isWaitingForTcpConfig = true;
        break;
    }
    default:
        updateMainResponse("错误：未知的配置页面");
        return;
    }

    currentQueryTab = currentTabIndex;
    lastCommand = command.trimmed();
    isWaitingForResponse = true;
    serialPort->write(command.toUtf8());
    serialPort->flush();
    updateMainResponse("发送查询命令: " + command.trimmed());
    startResponseTimer();
}

void frmserialport::sendConfigModeCommand(bool enter)
{
    QString command = enter ? Config::enterConfigMode() : Config::exitConfigMode();
    QSerialPort *serialPort = mainWindow->getSerialPort();
    if (serialPort->isOpen()) {
        lastCommand = command.trimmed();
        isWaitingForResponse = true;
        serialPort->write(command.toUtf8());
        serialPort->flush();
        updateMainResponse(enter ? "已发送进入设置模式命令 ($CFG+)" : "已发送退出设置模式命令 ($CFG-)");
        startResponseTimer();
    }
}

void frmserialport::enableConfigControls(bool enable)
{
    ui->nmeaMsgIdComboBox->setEnabled(enable);
    ui->nmeaRateLineEdit->setEnabled(enable);
    ui->rtcmMsgTypeLineEdit->setEnabled(enable);
    ui->rtcmRateLineEdit->setEnabled(enable);
    ui->baseStationAutoCheckBox->setEnabled(enable);
    ui->baseStationLatLineEdit->setEnabled(enable && !ui->baseStationAutoCheckBox->isChecked());
    ui->baseStationLonLineEdit->setEnabled(enable && !ui->baseStationAutoCheckBox->isChecked());
    ui->baseStationHeightLineEdit->setEnabled(enable && !ui->baseStationAutoCheckBox->isChecked());
    ui->sendBaseStationButton->setEnabled(enable);
    ui->sendMobileStationButton->setEnabled(enable);
    ui->gyroRateLineEdit->setEnabled(enable);
    ui->accelRateLineEdit->setEnabled(enable);
    ui->sendConfigButton->setEnabled(enable);
    ui->cancelButton->setEnabled(enable);
    enableTcpConfigControls(enable);
}

void frmserialport::resetConfigFields()
{
    ui->nmeaMsgIdComboBox->setCurrentIndex(0);
    ui->nmeaRateLineEdit->clear();
    ui->rtcmMsgTypeLineEdit->clear();
    ui->rtcmRateLineEdit->clear();
    ui->baseStationAutoCheckBox->setChecked(true);
    ui->baseStationLatLineEdit->clear();
    ui->baseStationLonLineEdit->clear();
    ui->baseStationHeightLineEdit->clear();
    ui->gyroRateLineEdit->clear();
    ui->accelRateLineEdit->clear();
    resetTcpConfigFields();
}

void frmserialport::onSerialDataReceived(const QString &data)
{
    if (!isWaitingForResponse) {
        return;
    }

    parseDeviceResponse(data);
}

void frmserialport::parseDeviceResponse(const QString &data)
{
    if (data == "$OK") {
        updateMainResponse("设备响应成功: 配置已应用");
        isWaitingForResponse = false;
        isWaitingForTcpConfig = false;
        responseTimer.stop();
    } else if (data == lastCommand) {
        updateMainResponse("设备响应成功: " + data);
        isWaitingForResponse = false;
        isWaitingForTcpConfig = false;
        responseTimer.stop();
    } else if (data.startsWith("$CFG+")) {
        updateMainResponse("设备已进入设置模式");
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$CFG-")) {
        updateMainResponse("设备已退出设置模式");
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$NMEA,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 0) {
            updateNmeaConfig(data);
        }
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$RTCM,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 1) {
            updateRtcmConfig(data);
        }
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$MODE,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 2) {
            updateBaseStationConfig(data);
        }
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$GYRO,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 3) {
            updateGyroConfig(data);
        }
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$ACEL,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 4) {
            updateAccelConfig(data);
        }
        isWaitingForResponse = false;
        responseTimer.stop();
    } else if (data.startsWith("$TCPS,")) {
        updateMainResponse("设备返回: " + data);
        if (currentQueryTab == 5 && isWaitingForTcpConfig) {
            updateTcpConfig(data);
        }
        isWaitingForResponse = false;
        isWaitingForTcpConfig = false;
        responseTimer.stop();
    } else {
        updateMainResponse("设备响应不匹配: " + data);
    }
}

void frmserialport::updateNmeaConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() < 3) {
        updateMainResponse("错误：设备返回的 NMEA 配置格式无效");
        return;
    }

    bool ok;
    int msgId = parts[1].trimmed().toInt(&ok);
    if (!ok || msgId < 0 || msgId >= ui->nmeaMsgIdComboBox->count()) {
        updateMainResponse("错误：设备返回的 NMEA 消息 ID 无效");
        return;
    }

    double rate = parts[2].trimmed().toDouble(&ok);
    if (!ok) {
        updateMainResponse("错误：设备返回的 NMEA 频率无效");
        return;
    }

    ui->nmeaMsgIdComboBox->setCurrentIndex(msgId);
    ui->nmeaRateLineEdit->setText(QString::number(rate));
    updateMainResponse("NMEA 配置已更新: 消息 ID = " + QString::number(msgId) + ", 频率 = " + QString::number(rate));
}

void frmserialport::updateRtcmConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() < 3) {
        updateMainResponse("错误：设备返回的 RTCM 配置格式无效");
        return;
    }

    bool ok;
    int msgType = parts[1].trimmed().toInt(&ok);
    if (!ok) {
        updateMainResponse("错误：设备返回的 RTCM 消息类型无效");
        return;
    }

    double rate = parts[2].trimmed().toDouble(&ok);
    if (!ok) {
        updateMainResponse("错误：设备返回的 RTCM 频率无效");
        return;
    }

    ui->rtcmMsgTypeLineEdit->setText(QString::number(msgType));
    ui->rtcmRateLineEdit->setText(QString::number(rate));
    updateMainResponse("RTCM 配置已更新: 消息类型 = " + QString::number(msgType) + ", 频率 = " + QString::number(rate));
}

void frmserialport::updateBaseStationConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() < 2) {
        updateMainResponse("错误：设备返回的基准站/移动站配置格式无效");
        return;
    }

    bool ok;
    int devMode = parts[1].trimmed().toInt(&ok);
    if (!ok || (devMode != 0 && devMode != 1)) {
        updateMainResponse("错误：设备返回的 DevMode 无效");
        return;
    }

    if (devMode == 1) {
        updateMainResponse("当前配置为基准站");
        ui->baseStationAutoCheckBox->setChecked(true);
    } else {
        updateMainResponse("当前配置为移动站");
        ui->baseStationAutoCheckBox->setChecked(false);
    }
}

void frmserialport::updateGyroConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() < 2) {
        updateMainResponse("错误：设备返回的陀螺计配置格式无效");
        return;
    }

    bool ok;
    double rate = parts[1].trimmed().toDouble(&ok);
    if (!ok) {
        updateMainResponse("错误：设备返回的陀螺计频率无效");
        return;
    }

    ui->gyroRateLineEdit->setText(QString::number(rate));
    updateMainResponse("陀螺计频率已更新: " + QString::number(rate));
}

void frmserialport::updateAccelConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() < 2) {
        updateMainResponse("错误：设备返回的加速度计配置格式无效");
        return;
    }

    bool ok;
    double rate = parts[1].trimmed().toDouble(&ok);
    if (!ok) {
        updateMainResponse("错误：设备返回的加速度计频率无效");
        return;
    }

    ui->accelRateLineEdit->setText(QString::number(rate));
    updateMainResponse("加速度计频率已更新: " + QString::number(rate));
}

void frmserialport::startResponseTimer()
{
    responseTimer.start(5000); // 5 秒超时
}

void frmserialport::enableTcpConfigControls(bool enable)
{
    ui->tcpIpLineEdit->setEnabled(enable);
    ui->tcpPortLineEdit->setEnabled(enable);
    ui->tcpDevIdLineEdit->setEnabled(enable);
}

void frmserialport::resetTcpConfigFields()
{
    ui->tcpIpLineEdit->clear();
    ui->tcpPortLineEdit->clear();
    ui->tcpDevIdLineEdit->clear();
}

void frmserialport::updateTcpConfig(const QString &data)
{
    QStringList parts = data.split(",");
    if (parts.size() != 4) {
        updateMainResponse("错误：设备返回的 TCP 配置格式无效");
        return;
    }

    QString ip = parts[1].trimmed();
    QString port = parts[2].trimmed();
    QString devId = parts[3].trimmed();

    if (ip.isEmpty() || devId.isEmpty()) {
        updateMainResponse("错误：设备返回的 TCP IP 或设备 ID 为空");
        return;
    }

    bool ok;
    int portNum = port.toInt(&ok);
    if (!ok || portNum < 1 || portNum > 65535) {
        updateMainResponse("错误：设备返回的 TCP 端口号无效（必须为 1-65535 之间的整数）");
        return;
    }

    ui->tcpIpLineEdit->setText(ip);
    ui->tcpPortLineEdit->setText(port);
    ui->tcpDevIdLineEdit->setText(devId);
    updateMainResponse("TCP 配置已更新: IP = " + ip + ", 端口 = " + port + ", 设备 ID = " + devId);
}